<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="displayModuleTitle"
    @ok="onButtonOkClick"
    width="550px"
  >
    <BasicForm @register="registerForm">
      <template #bgimg="{ model, field }">
        <a-upload-dragger
          :file-list="fileList"
          name="file"
          :maxCount="1"
          accept=".svg"
          :custom-request="upload"
          @remove="removeFile"
          @change="changeFile"
          @download="viewSvg"
          :showUploadList="{
            showRemoveIcon: true,
          }"
        >
          <!-- <p class="ant-upload-drag-icon">
            <CloudUploadOutlined />
          </p> -->
          <p class="ant-upload-hint"> 请点击或拖拽上传单元空间分布图 </p>
        </a-upload-dragger>
      </template>
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent, ref, unref, computed, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { getUnitDivision, addUnitDivision, updateUnitDivision } from '/@/api/ehs/unitDivision';
  import { addOrUpdateUnitDivisionSchema } from './unitDivision.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { useGlobSetting } from '/@/hooks/setting';
  import { getUserOrganization } from '/@/api/ehs/organization';
  import { uploadApi } from '/@/api/platform/upload';
  import { CloudUploadOutlined } from '@ant-design/icons-vue';
  import { getFileApi } from '/@/api/platform/file';
  const { globalProjectCode } = useGlobSetting();
  const { createMessage } = useMessage();
  import { downloadByUrl } from '/@/utils/file/download';
  import { queryUnitDivision } from '/@/api/ehs/unitDivision';
  export default defineComponent({
    name: 'AddOrUpdateUnitDivision',
    components: { BasicModal, BasicForm, CloudUploadOutlined },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //弹出窗口界面是新增数据、修改数据；根据传递过来的参数进行判断
      const operateType = ref(OperationTypeEnum.UN_KNOWN);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const dataId = ref<String>('');
      const projectCode = ref<String>(globalProjectCode);
      const organizationCode = ref();
      const fileId = ref();
      const fileList = ref([]);
      const unitInfo = ref({});
      const { uploadUrl } = useGlobSetting();
      const getImageFileUrlPrefix = ref<string>(uploadUrl + getFileApi);
      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
        labelWidth: 100,
        schemas: addOrUpdateUnitDivisionSchema,
        showActionButtonGroup: false,
        scrollToFirstError: true,
        actionColOptions: {
          span: 24,
        },
      });

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.operateType) {
            //判断是否传入op属性
            operateType.value = unrefData.operateType;
          }
          if (unrefData?.dataId) {
            dataId.value = unrefData.dataId;
          }
        }
        resetFields(); //重置表单
        setModalProps({ confirmLoading: false });
        getUserOrganization(projectCode.value).then((res) => {
          organizationCode.value = res ? res.orgcode : null;
          queryUnitDivision({
            includechilds: true,
            isdept: false,
            flagisvalid: false,
            orgcode: organizationCode.value,
          })
            .then((res) => {
              //父级单元选项集合
              updateSchema({
                field: 'parentid',
                componentProps: {
                  treeData: operateType.value == OperationTypeEnum.EDIT ? deepFilter(res) : res,
                  fieldNames: { label: 'unitname', value: 'unitid', children: 'children' },
                  treeDefaultExpandAll: true, //默认展开
                  listHeight: 250, //设置弹窗滚动高度
                },
              });
            })
            .catch((ex) => {
              console.log('catch ', ex);
            });
        });

        // 如果是修改数据，根据传入的id获取数据后进行赋值
        if (operateType.value == OperationTypeEnum.EDIT) {
          getUnitDivisionById();
        }
      });

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      function getUnitDivisionById() {
        getUnitDivision(dataId.value)
          .then((res) => {
            console.log('res', res);
            unitInfo.value = res;
            setFieldsValue({
              ...res,
            });
            fileId.value =
              res.bgimg && JSON.parse(res.bgimg).id ? JSON.parse(res.bgimg).id : undefined;
            fileList.value = res.bgimg && JSON.parse(res.bgimg).id ? [JSON.parse(res.bgimg)] : [];
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }
      /**
       * 点击确认按钮，根据不同的op调用对应方法保存信息
       */
      async function onButtonOkClick() {
        if (fileId.value == undefined || fileId.value == null) {
          console.log('无上传svg文件');
        }
        const values = await validate().catch((e) => {
          scrollToFirstError();
          throw e;
        });
        setModalProps({ confirmLoading: true });
        values.orgcode = organizationCode.value;
        values.bgimg = fileId.value
          ? JSON.stringify({
              name: fileList.value[0]?.name,
              status: fileList.value[0]?.status,
              id: fileId.value,
              url: fileId.value,
            })
          : '';
        //根据指定的操作类型分别进行提交数据和处理
        if (operateType.value == OperationTypeEnum.ADD) {
          //对应操作的步骤为：验证表单、提交后台保存、关闭modal、调用父组件事件刷新数据
          try {
            //调用接口进行保存
            addUnitDivision({ ...unitInfo.value, ...values })
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('保存成功。', 2);
                }
                opSuccess();
              })
              .catch((ex) => {
                console.log('catch ', ex);
                setModalProps({ confirmLoading: false });
              });
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } else if (operateType.value == OperationTypeEnum.EDIT) {
          //调用接口进行保存
          updateUnitDivision({ ...unitInfo.value, ...values })
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('修改成功。', 2);
              }
              opSuccess();
            })
            .catch((ex) => {
              console.log('catch ', ex);
              setModalProps({ confirmLoading: false });
            });
        } else {
          createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
        }
      }
      // 过滤单元菜单,不让选自己以及自己的子级单元作为上级单元
      function deepFilter(arr) {
        return arr.filter((item) => {
          if (item.children) item.children = deepFilter(item.children);
          return item.unitid != dataId.value;
        });
      }
      //操作成功后
      function opSuccess() {
        emit('success');
        closeModal();
      }

      function upload(info) {
        const fileType = info.file.name.split('.').pop();
        // 获取文件类型,如果是svg或者png文件则上传,否则提示文件格式错误
        if (fileType === 'svg') {
          uploadApi({ system: 'ehs', file: info.file, module: 'attachment' })
            .then((res) => {
              if (res.data.data.success) {
                fileId.value = res.data.data.fileid;
                createMessage.success('上传成功');
                info.onSuccess(res.data, info);
              } else {
                fileId.value = undefined;
                createMessage.error('上传失败,请稍后重试');
                fileList.value[0].status = 'error';
              }
            })
            .catch((err) => {
              fileId.value = undefined;
              createMessage.error('上传失败,请稍后重试');
              fileList.value[0].status = 'error';
            });
        } else if (fileType !== 'svg') {
          fileId.value = undefined;
          createMessage.error('文件格式不符,请上传svg文件');
          fileList.value[0].status = 'error';
        }
      }
      function removeFile() {
        // 移除上传的文件,清空文件数据
        fileId.value = undefined;
        fileList.value = [];
      }

      function changeFile(e) {
        fileList.value = e.fileList;
      }

      function viewSvg(file) {
        console.log(file, 'file');
        if (fileId.value) {
          window.open(getImageFileUrlPrefix.value + fileId.value);
        } else {
          createMessage.error('请先上传文件');
        }
      }

      const scrollToFirstError = () => {
        document
          .querySelector('.ant-form-item-has-error')
          ?.scrollIntoView({ behavior: 'smooth', block: 'center' });
      };

      onMounted(() => {
        // 新增时需要传入用户有效组织
      });
      return {
        operateType,
        organizationCode,
        displayModuleTitle,
        fileId,
        fileList,
        viewSvg,
        changeFile,
        registerModal,
        upload,
        removeFile,
        registerForm,
        getUnitDivisionById,
        onButtonOkClick,
        opSuccess,
        getImageFileUrlPrefix,
      };
    },
  });
</script>

<style scoped></style>
